const koa = require("koa");
const app =  new koa();
const router = require("koa-router")();
const main = require("./models")
const koaBody = require("koa-body");
const fs = require("fs");
const path = require("path");
const static = require("koa-static");
router.get("/find",async ctx=>{
    
    var  collection = await main();
    var  result = await collection.find().toArray();
    ctx.body = result;
})
router.get("/add",async ctx=>{

    var  collection = await main();
    var obj = {
        name:"吴章",
        age:17
    }
    
    var res = await collection.find({name:obj.name}).toArray();
    if(res.length){
        ctx.body = "数据库中已经添加了这位同学"
    }else{
        var result =  await collection.insertOne(obj);
        console.log(result)
    }
})
router.post("/doForm",async ctx=>{
    var {name,age} = ctx.request.body;
    age = Number(age);
    var filename = ctx.request.files.logo.path
    /* 1、创建一个可读流 */
    var reader = fs.createReadStream(filename);
    /* 2、设置上传的文件名 */
    var uploadFile = `./static/${path.basename(filename)}`;
    /* 3、创建一个可写流 */
    var writer = fs.createWriteStream(uploadFile);
    /* 4、通过管道将可读流写入可写流 */
    reader.pipe(writer);
    // console.log(ctx.origin)
    var logo = ctx.origin +"/"+path.basename(filename);
    
    const collection = await main();
    await collection.insertOne({name,age,logo});
    await ctx.redirect("/find")
})
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024,    
		keepExtensions: true
    }
}))
app.use(static(path.join(__dirname,"static")))
app.use(async (ctx,next)=>{
    ctx.set("Access-Control-Allow-Origin","*");
    await next();
})
app.use(router.routes());
app.listen(4100);